<template>
  <div class="third-node">
    <el-form label-position="top" :rules="rules" label-width="80px" :model="formData" ref='nodeForm'>
      <div v-for="(item, index) in formData.inputParams" :key="item.paramKey">
        <div class="params-item">
          <el-form-item v-if="item.specs" :label='item.paramName' :prop="`inputParams[${index}].value`" :rules="rules.select" class="params-item-form">
            <el-select v-model="item.value" placeholder="请选择">
              <el-option v-for="option in item.specs" :key="option.key" :label="option.name" :value="option.key"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-else-if="item.category === 'video' || item.category === 'picture'" :label='item.paramName' :prop="`inputParams[${index}].value`" :rules="rules.upload" class="params-item-form">
            <div v-if="!item.value" class="upload-area" style="display: flex">
              <el-upload v-loading='uploading' :file-list="item.fileList" class="" :before-upload="file => beforeUpload(file, item.category)" :on-success="res => handleSuccess(res, item)" :action="`${baseURL}/design/business/ecology/upload`" :headers="headers" :show-file-list="false">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
              <span style="color: #C0C4CC;margin-left: 6px"> （只能上传{{item.category === 'picture' ? 'jpg/jpeg/png' : 'mp3/mp4/mov'}}文件）</span>
            </div>
            <div v-else class="file-info">
              <i class="el-icon-document file-icon"></i>
              <span @click="downFile(item)">{{ formatFileName(item.fileName) }}</span>
              <span @click="removeFile(item)"><i class="el-icon-close"></i></span>
            </div>
          </el-form-item>
          <el-form-item v-else-if="item.category === 'String'" :label='item.paramName' :prop="`inputParams[${index}].value`" :rules="rules.input" class="params-item-form">
            <el-input v-model="item.value" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item v-else :prop="`inputParams[${index}].value`" :label='item.paramName' :rules="rules.input" class="params-item-form">
            <el-input-number v-model="item.value" :precision="item.category === 'Integer' ? 0 : undefined" placeholder="请输入" :controls='false' class="input-number"></el-input-number>
          </el-form-item>
          <div class="tool-bar">
            <svg-icon :icon-class="`参数${item.openParam.isOpen ? '已' : '未'}开放`" :className="`${item.openParam.isOpen} signal-open`" @click="paramOpen(item)"/>
          </div>
        </div>
        <ParamOpen :show.sync='item.showParamOpen' :openParam.sync='item.openParam' :signalItem='item' ref='paramOpen'></ParamOpen>
      </div>
      <el-form-item v-if="formData.metaModelId" label="选择模板" prop="templateId">
        <el-select v-model="formData.templateId" @change="changeTemp" placeholder="请选择">
          <el-option v-for="option in serviceItem.templateList" :key="option.id" :label="option.name" :value="option.id">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div v-if="tempItem" class="temp-detail">
      <img :src="tempItem.imageUrl" class="temp-img"/>
      <el-button v-if="tempItem.imageUrl" type="text" @click="showPic = true" class="show-img">查看大图</el-button>
    </div>
    <el-dialog v-if="tempItem" :visible.sync="showPic" title="查看大图" width="1200px" append-to-body custom-class='third-node-pic-dialog'>
      <img :src="tempItem.imageUrl" class="temp-img"/>
    </el-dialog>
  </div>
</template>

<script>
import ThirdNodeApi from '@/api/ruleNode/thirdNode'
import { deepClone } from '@/utils/helper/jsUtil'
import { getToken } from '@/utils/auth'
import ParamOpen from './paramOpen.vue'
import { generatorTreeSelectData, adapterServiceItemData } from './thirdNode.util'
import RuleNodeBaseClass from '@/components/ruleNode/RuleNodeBaseClass'

export default {
  name: 'ThirdLibThirdNode',
  mixins: [RuleNodeBaseClass],
  components: {
    ParamOpen
  },
  data() {
    return {
      baseURL: process.env.VUE_APP_AJAX_BASE_URL,
      headers: { Authorization: 'Bearer ' + getToken() },
      fileList: [],
      formData: {
        metaModelId: '',
        templateId: '',
        serviceName: '',
        serviceKey: '',
        inputParams: []
      },
      options: [],
      serviceItem: {
        templateList: []
      },
      tempItem: {},
      showPic: false,
      uploading: false,
      rules: {
        templateId: [{ required: true, message: '请选择', trigger: 'change' }],
        metaModelId: [{ required: true, message: '请选择', trigger: 'change' }],
        select: [{ required: true, message: ' ', trigger: 'change' }],
        upload: [{ required: true, message: '请上传', trigger: 'change' }],
        input: [{ required: true, message: ' ', trigger: 'blur' }]
      }
    }
  },
  mounted() {
  },
  methods: {
    async getEcologyServices() {
      const { getEcologyServices } = ThirdNodeApi
      const res = await getEcologyServices()
      this.serviceListData = res.data
      this.options = res.data.options
    },
    handleChange(metaModelId) {
      metaModelId && this.getServiceItem(metaModelId)
      this.tempItem = {}
      this.formData.templateId = ''
    },
    beforeUpload(file, type) {
      const isAcc = {
        video: ['audio/mpeg', 'video/mp4', 'video/quicktime'],
        picture: ['image/jpg', 'image/jpeg', 'image/png']
      }
      if (!isAcc[type].includes(file.type)) {
        this.$message.error('上传文件格式错误!')
        return false
      }
      this.uploading = true
    },
    handleSuccess(res, item) {
      this.uploading = false
      if (res.code === 200 && res.data) {
        this.$message({ type: 'success', message: '上传成功' })
        item.value = res.data.filePath
        item.fileName = res.data.fileName
        this.$refs.nodeForm.clearValidate()
      } else {
        this.$message({ type: 'error', message: res.msg })
      }
    },
    downFile(item) {
      window.location.href = item.value
    },
    removeFile(item) {
      item.value = ''
      item.fileName = ''
    },
    getServiceItem(metaModelId) {
      const serviceItem = this.serviceListData.services.find(el => el.id === metaModelId.at(-1))
      serviceItem && (this.formData.inputParams = adapterServiceItemData(serviceItem))
      serviceItem && (this.serviceItem = serviceItem)
      this.formData.serviceName = this.serviceItem.name
      this.formData.serviceKey = this.serviceItem.identifier
    },
    changeTemp(val) {
      this.tempItem = this.serviceItem.templateList.find(item => item.id === val)
    },
    formatFileName(name) {
      let res = name
      if (name.length > 28) {
        res = res.slice(0, 12) + '...' + res.slice(-16)
      }
      return res
    },
    paramOpen(item) {
      item.showParamOpen = !item.showParamOpen
      if (!item.showParamOpen) {
        this.$refs.paramOpen[0].resetForm()
      }
    },
    async initValue() {
      const initFormData = this.initialForm ? deepClone(this.initialForm) : {}
      await this.getEcologyServices()
      // 生态服务与TSP服务不同 ，以metaModelId作为唯一标识，而非serviceKey
      if (initFormData.metaModelId) {
        initFormData.metaModelId = generatorTreeSelectData(this.options, initFormData.metaModelId)
        this.getServiceItem(initFormData.metaModelId)
        initFormData.inputParams = initFormData.inputParams || this.formData.inputParams
        initFormData.templateId && this.changeTemp(initFormData.templateId)
      }
      Object.assign(this.formData, initFormData)
    },
    getFormData() {
      const data = deepClone(this.formData)
      data.metaModelId = data.metaModelId.at(-1)
      return data
    },
    validateForm() {
      let isValid
      this.$refs.nodeForm.validate(valid => { isValid = valid })
      return isValid
    }
  }
}
</script>

<style lang="scss">

.third-node {
  .service-cascader{
    display: block;
  }
  .input-number{
    width: 100%;
    .el-input__inner{
      text-align: left;
    }
  }
  .params-item{
    display: flex;
    align-items: flex-end;
    .params-item-form{
      flex: 1 0 auto;
      margin-bottom: 8px;
    }
    .input-description{
      position: absolute;
      right: 4px;
      font-size: 16px;
      display: block;
      top: 0;
      line-height: 32px;
      color: #a3a3a3;
    }
    .setting-select-label{
      white-space: nowrap;
    }
    .setting-select{
      flex: 0 1 140px;
      .select-type{
        width: 132px;
      }
    }
    .tool-bar{
      margin-bottom: 8px;
      .signal-open{
        width: 16px;
        height: 32px;
        cursor: pointer;
        margin-left: 24px;
        margin-right: 2px;
        &.true{
          width: 18px;
          margin-right: 0;
        }
      }
    }
    .upload-area{
      height: 32px;
    }
    .file-info{
      line-height: 32px;
      height: 32px;
      display: flex;
      &:hover{
        .file-icon, span, .el-icon-close{
          background-color: #eee;
        }
      }
      .file-icon{
        line-height: 32px;
        font-size: 18px;
        padding-right: 10px;
      }
      span{
        line-height: 32px;
        padding-right: 10px;
      }
      .el-icon-close{
        cursor: pointer;
        &:hover{
          color: #5e7fff;
        }
      }
    }
  }
  .temp-detail{
    display: flex;
    align-items: flex-end;
    .temp-img{
      width: 300px;
    }
    .show-img{
      margin-left: 10px;
      padding-bottom: 0;
    }
  }
}
</style>
<style lang="scss">
.third-node-pic-dialog{
  .el-dialog__body{
    max-height: 80vh;
    .temp-img{
      width: 100%;
      line-height: 0;
      vertical-align: top;
    }
  }
}
</style>
